#!/usr/bin/env node

const http = require('http'),
      fs = require('fs'),
      datalist = require('./data.js'),
      url = require('url');

function getData(){
  datalist.chapterList.sort((a,b)=>{
    let str = a.publishTimer.split('-');
    let str2 = b.publishTimer.split('-');
    let num = 365*parseInt(str[0])+30*parseInt(str[1])+parseInt(str[2]);
    let num2 = 365*parseInt(str2[0])+30*parseInt(str2[1])+parseInt(str2[2]);
    return num2-num;
  });
  let data = JSON.stringify(datalist.chapterList);
   
  return data;
}

function getPage(){
  let html = fs.readFileSync('./chapters.html').toString('utf8');
  return html.replace('<head>','<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>');
}

function getPagePuls(id){
  let html = `<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>${id}</title>
    </head>
    <body>
    <p>${datalist.chapterList[id].chapterContent}</p>
    <p>${datalist.chapterList[id].chapterDes}</p>
    </body>
  </html>`;
  return html;
}

http.createServer((req,res)=>{
  let addr = url.parse(req.url);
  let str = addr.href.split('?');
  console.log(str);
  if(addr.pathname === '/getlist'){
    res.writeHead(200,{
      'Content-Type':'application/json',
      'Content-length':Buffer.byteLength(getData())
    });
    res.end(getData());
  }
  else if(addr.pathname === '/'){
    res.writeHead(200,{
      'Content-Type':'text/html',
      'Content-length':Buffer.byteLength(getPage())
    });
    res.end(getPage());
  }
  else if(str[0] === '/detail'){
    let id = str[1].split('=');
    id = parseInt(id[1]);
    console.log(id);
    console.log(datalist.chapterList[id-1]);
    res.writeHead(200,{
      'Content-Type':'text/html',
      'Content-length':Buffer.byteLength(getPagePuls(id-1))
    });
    res.end(getPagePuls(id-1));
  }
  else{
    fs.createReadStream(`.${addr.pathname}`).pipe(res);
  }
}).listen(8080);
